package com.ikai.ruderesponser;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class RecentRudenessServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
	    throws IOException, ServletException {
	UserService userService = UserServiceFactory.getUserService();
	User user = userService.getCurrentUser();
	if (user != null) {
	    DatastoreService datastore = DatastoreServiceFactory
		    .getDatastoreService();

	    Query query = new Query("Use");
	    query.addFilter("userId", FilterOperator.EQUAL, user.getUserId());
	    query.addSort("timestamp", SortDirection.DESCENDING);
	    List<Entity> uses = datastore.prepare(query).asList(
		    FetchOptions.Builder.withLimit(50));

	    req.setAttribute("uses", uses);
	    req.getRequestDispatcher("WEB-INF/recent.jsp").forward(req, resp);

	} else {
	    resp.sendRedirect(userService.createLoginURL("/"));
	}
    }
}
